//
//  CJControl.m
//  TMSDriver
//
//  Created by mac on 2019/2/12.
//  Copyright © 2019年 zhuchongjin. All rights reserved.
//

#import "CJControl.h"
#import "GTMBase64.h"
#import <CommonCrypto/CommonDigest.h>
#import <Foundation/Foundation.h>
#import <SAMKeychain/SAMKeychain.h>
@implementation CJControl

+(void)clearAllUserDefaultsData{

    NSUserDefaults*userDefaults = [NSUserDefaults  standardUserDefaults];
    NSDictionary*dic = [userDefaults  dictionaryRepresentation];
    for(id key in dic) {
        
        if ([key isEqualToString:CJMainURLChange] || [key isEqualToString:@"isFirstLogInSucess"] || [key isEqualToString:@"StrongReminderTag"]) {

        }else{
            [userDefaults  removeObjectForKey:key];
        }
        
    }
   [userDefaults  synchronize];
}

#pragma mark ----------判断是否第一次登陆成功

/// 判断是否第一次登陆成功
+ (BOOL)getIsFirstLogInSucess {
    
    BOOL coachMarksShown = [[NSUserDefaults standardUserDefaults] boolForKey:@"isFirstLogInSucess"];
    if (coachMarksShown == NO) {
        // Don't show again
        [[NSUserDefaults standardUserDefaults] setBool:YES forKey:@"isFirstLogInSucess"];
        [[NSUserDefaults standardUserDefaults] synchronize];
        return YES;
    }else{
        return NO;
    }
}

//#pragma mark ----------登录返回信息处理-------
//
//+ (NSDictionary *)getLogInReponseInfor{
//
//    return CJFetchMyDefault(CJLogInResponseInfo);
//}
//
//
//// 获取 登录信息里面的 branch 信息
//
//+ (NSDictionary *)getLogInReponseBranch{
//    NSDictionary *dic = [[CJControl getLogInReponseInfor] objectForKey:@"branch"];
//
//    return dic;
//}

/// code  base64 加密
//+ (NSString *)getCodeWithBase64{
//
//    NSString *code = [[NSString alloc]init];
//    NSDictionary *dic = [CJControl getLogInReponseInfor];
//
//    if (dic == nil || IsNilOrNull(dic)) {
//        code = @"";
//
//    } else {
//        code = [CJControl base64:[dic objectForKey:@"code"]];
//    }
//    return code;
//}
//
//+ (NSString *)getCode{
//
//    NSString *code = [[NSString alloc]init];
//    NSDictionary *dic = [CJControl getLogInReponseInfor];
//
//    if (dic == nil || IsNilOrNull(dic)) {
//        code = @"";
//
//    } else {
//        code = [dic objectForKey:@"code"];
//    }
//    return code;
//}
//

+ (BOOL)isLogin{
    if (IsStrEmpty(CJFetchMyDefault(CJLogInResponseToken))) {
        return NO;
    }else{
        return YES;
    }
}

+ (NSDictionary *)getBranch{
    
    NSDictionary *dic = CJFetchMyDefault(CJLogInResponseBranch);
    
 
    return dic;
}


+ (NSString *)getBranchCode{
    
    NSString *code = CJFetchMyDefault(CJBranchCode);

    if (IsNilOrNull(code) || [CJControl getIsEmpty:code] || IsStrEmpty(code)) {
        return BranchCode;
    }else{
        return code;
    }
   
}

+ (NSString *)getServePhoneNum{

    NSDictionary * dic = [CJControl getBranch];
    return [CJControl getThreeUnaryValueStr:dic[@"mobilePhone"]];
}

// 获取系统参数设置s
+ (NSString *)getSecondUploadDetail{
    
    NSDictionary * dic = [CJControl getBranch];
    NSDictionary *partyGroupConfigCacheMap = dic[@"partyGroupConfigCacheMap"];
    if (partyGroupConfigCacheMap == nil || IsNilOrNull(partyGroupConfigCacheMap)) {
        return @"0";
    }else{
        NSDictionary *orderDetailOperate_secondUploadDetail = partyGroupConfigCacheMap[@"orderDetailOperate_secondUploadDetail"];
        if (orderDetailOperate_secondUploadDetail == nil || IsNilOrNull(orderDetailOperate_secondUploadDetail)) {
            return @"0";
        }else{
            
            return orderDetailOperate_secondUploadDetail[@"configValue"];
        }
    }
    
//    return @"1";
}

//+ (NSString *)getName{
//    return [[CJControl getLogInReponseInfor] objectForKey:@"name"];
//}
//+ (NSString *)getPhone{
//    return [[CJControl getLogInReponseInfor] objectForKey:@"phone"];
//}


#pragma mark ----------登陆 返回的信息部分

+ (NSDictionary *)getShippmenInfo{
    
    NSDictionary *dic = CJFetchMyDefault(CJLogInResponseShippmentInfo);
    
    return dic;
}

+ (BOOL)getIsCompany{
    
   //SHIPMENT SHIPMENT   独立货主
   //SHIPMENT_COMPANY  发货企业
    
    NSDictionary *dic = [CJControl getShippmenInfo];
    
    if (dic == nil || IsNilOrNull(dic) ) {
        return NO;
    }else {
        NSString *strCode = dic[@"partyType"];
        if ([strCode isEqualToString:@"SHIPMENT"]) {
            return NO;
        }else{
            return YES;
        }
    }
    
//    return YES;
}

+ (NSString *)getPartyCode{
    
    NSDictionary *dic = [CJControl getShippmenInfo];
    
    return [CJControl getThreeUnaryValueStr:dic[@"code"]];
}


#pragma mark ------- PartyGroupDefault

+ (NSDictionary *)getPartyGroupDefault{
    NSDictionary *dic = CJFetchMyDefault(CJPartyGroupDefault);
    return dic;
}

/// 获取客服电话
+ (NSString *)getCustomerServicePhone{
    
    NSDictionary *dic = [CJControl getPartyGroupDefault];
    return [CJControl getThreeUnaryValueStr:dic[@"telephone"]];
}

/// 获取全国客服电话
+ (NSString *)getCustomerServiceqgPhone{
    
    NSDictionary *dic = [CJControl getPartyGroupDefault];
    return [CJControl getThreeUnaryValueStr:dic[@"complainLine"]];
}

/// 登陆是否需要 短信验证   yes 需要 其他均不需要
+ (BOOL)getIsLoginNeedSMS{

    NSDictionary *dic = [CJControl getPartyGroupDefault];
    NSString *isLoginNeedSMS = [CJControl getThreeUnaryValueStr:dic[@"isLoginNeedSMS"]];
    return [isLoginNeedSMS isEqualToString:@"yes"] ? YES:NO;;
}


/// 是否隐藏分机构
+ (BOOL)getHideBranche{
    
//    iOS货主端登录页面是否隐藏机构信息，0否，1是  integer
    NSDictionary *dic = [CJControl getPartyGroupDefault];
    NSString *hidBranch = [CJControl getThreeUnaryValueStr:dic[@"hidBranch"]];
    return [hidBranch isEqualToString:@"1"] ? YES:NO;;
    
}

#pragma mark -------- 获取盐

+ (NSString *)getDefaultSalt{
    NSDictionary *dic = [CJControl getPartyGroupDefault];
    return [CJControl getThreeUnaryValueStr:dic[@"salt"]];
}


+ (BOOL)getUIWithNew{
    
//    NSDictionary *dic = [CJControl getPartyGroupDefault];

//    colorStyle = "blue", 正常
    
//    if (IsNilOrNull(dic)) {
//        return NO;
//    }else{
//
//        NSString *colorStyle = [CJControl getThreeUnaryValueStr:dic[@"colorStyle"]];
//        if ([colorStyle isEqualToString:@"blue"]) {
//            return NO;
//        }else{
//            return YES;
//        }
//    }
    
    return NO;
//    return YES;

}



#pragma mark ----userCenter

//CJSaveMyDefault(CJPartyUserCenter, (NSDictionary *)responseObject);

+ (NSDictionary *)getPartyUserCenter{
    NSDictionary *dic = CJFetchMyDefault(CJPartyUserCenter);
    return dic;
}


/// 获取登陆电话
+ (NSString *)getLogInPhoneNum{
    NSDictionary *dic = [CJControl getPartyUserCenter];
    return [CJControl getThreeUnaryValueStr:dic[@"phone"]];
}

+ (NSInteger )getIsIndependentCheckout{

//isIndependentCheckout (integer, optional): 是否独立核算:0否/1是 ,
    NSDictionary *dic = [CJControl getPartyUserCenter];
    if (dic == nil || IsNilOrNull(dic) ) {
        return 0;
    }else {
        NSString *strCode = CJStringWithFormat(@"%@",dic[@"isIndependentCheckout"]);
        if ([strCode isEqualToString:@"1"]) {
            return 1;
        }else{
            return 0;
        }
    }
}


//@ApiModelProperty(value = "角色，0-独立货主，1-企业货主，2-企业发货人，3-企业财务，4-企业收货人，5-上游客户，6-代付机构")
//   private Integer staffType;

+ (BOOL)getIsCompanyStaff{
    
    NSDictionary *dic = [CJControl getPartyUserCenter];
    
    if (dic == nil || IsNilOrNull(dic) ) {
        return NO;
    }else {
        NSString *strCode = CJStringWithFormat(@"%@",dic[@"staffType"]);
        if ([strCode isEqualToString:@"1"] || [strCode isEqualToString:@"0"]) {
            return NO;
        }else{
            return YES;
        }
    }
    
    return  NO;
}

/// 企业和企业下的发货人
+ (BOOL)getIsCompanyAndStaff{
    
    NSDictionary *dic = [CJControl getPartyUserCenter];
    
    if (dic == nil || IsNilOrNull(dic) ) {
        return NO;
    }else {
        NSString *strCode = CJStringWithFormat(@"%@",dic[@"staffType"]);
        if ([strCode isEqualToString:@"0"] ) {
            return NO;
        }else{
            return YES;
        }
    }
    
    return  NO;
}

/// 税务开关 0关闭 1开启
+ (BOOL)getIsTax{
    
    NSDictionary *dic = [CJControl getPartyUserCenter];

    if (dic == nil || IsNilOrNull(dic) ) {
        return NO;
    }else {
        NSString *strCode = CJStringWithFormat(@"%@",dic[@"isTax"]);
        if ([strCode isEqualToString:@"1"]) {
            return YES;
        }else{
            return NO;
        }
    }
    
//    return  NO;
}


/// 电子签章 是否通过短信
+ (BOOL)getElecSignTypeByAouthCode{
    
    // 业务逻辑，根据userCenter接口中 elecSignType（电子签章方式 0非短信 1短信验证
    NSDictionary *dic = [CJControl getPartyUserCenter];

    if (dic == nil || IsNilOrNull(dic) ) {
        return NO;
    }else {
        NSString *strCode = CJStringWithFormat(@"%@",dic[@"elecSignType"]);
        if ([strCode isEqualToString:@"1"]) {
            return YES;
        }else{
            return NO;
        }
    }
}

/// 使用地图选点
+ (BOOL)getSelectAdressByAmap{
    
    // 上面的接口新增 返回值  fillAndSignLimitOnOff     （"1"/"0"   开/关）
    return [CJControl getBoolByKeyString:@"fillAndSignLimitOnOff"];
//    return YES;
//    return NO;
}
 
/// 证件到期预警
+ (BOOL)getIdCardDueWarn{
    // idcardDueWarn  1  0 证件到期预警
    return [CJControl getBoolByKeyString:@"idcardDueWarn"];
}

+ (NSInteger )getAccountAuthStatus{
    NSDictionary *dic = [CJControl getPartyUserCenter];
    NSString *strStatus = CJStringWithFormat(@"%@",dic[@"authStatus"]);
    return [strStatus integerValue];
}

//@ApiModelProperty(value = "身份证是否已经到期  1 是 0否")
//   private Integer idCardDateHasDue = 0;


/// 身份证是否已经到期  1 是 0否
+ (BOOL)getIdCardDateHasDue{
    // idCardDateHasDue  身份证是否已经到期  1 是 0否
    return [CJControl getBoolByKeyString:@"idCardDateHasDue"];
}

//CJSaveMyDefault(StrongReminderTag, StrongReminderShow);
///获取本地储存 强提醒是否展示
+ (BOOL)getStrongReminderShow{
    return [CJFetchMyDefault(StrongReminderTag) isEqualToString:StrongReminderHide] ? NO:YES;
}

/// 展示网商支付
+ (BOOL)getShowMyBank{
    
    //paymentType：arpa:中台集中支付，mybank:网商银行;arpa_2云企付二期
    //mybank:手动输入
    //arpa、arpa_2:选择     // 只有mybank 展示网商
    NSDictionary *dic = [CJControl getPartyUserCenter];
    if (dic == nil || IsNilOrNull(dic) ) {
        return NO;
    }else {
        NSString *strCode = CJStringWithFormat(@"%@",dic[@"paymentType"]);
        if ([strCode isEqualToString:@"mybank"]) {
            return YES;
        }else{
            return NO;
        }
    }
//    return YES;
}

/// 银行钱包信息
+ (BOOL)getShowAccounWallet{
    
    //paymentType：arpa:中台集中支付，mybank:网商银行;arpa_2云企付二期
    //mybank   arpa_2  展示全信息
    //arpa
    
    NSDictionary *dic = [CJControl getPartyUserCenter];
    if (dic == nil || IsNilOrNull(dic) ) {
        return NO;
    }else {
        NSString *strCode = CJStringWithFormat(@"%@",dic[@"paymentType"]);
        if ([strCode isEqualToString:@"arpa_2"]) {
            return YES;
        }else{
            return NO;
        }
    }
    
    return YES;
}


/// 获取支付类型
//+ (CJPaymentType )getPaymentType{
//    
//    //paymentType：arpa:中台集中支付，mybank:网商银行;arpa_2云企付二期
//    //mybank   arpa_2
//    //arpa
//
//    NSDictionary *dic = [CJControl getPartyUserCenter];
//    if (dic == nil || IsNilOrNull(dic) ) {
//        return CJDefaultPay;
//    }else {
//        NSString *strCode = CJStringWithFormat(@"%@",dic[@"paymentType"]);
//        if ([strCode isEqualToString:@"mybank"]) {
//            return CJMybankPay;
//        }else if([strCode isEqualToString:@"arpa_2"]){
//            return CJZhongXinPay;
//        }else if ([strCode isEqualToString:@"arpa"]){
//            return CJArpaPay;
//        }else{
//            return CJDefaultPay;
//        }
//    }
//
//}

//appRoleConfig =     (
//        {
//        id = "4392",
//        roleCode = "0e02dfb8b9fe447785985ba87d8c16d2",
//        configDesc = "待开票：0-否，1-是",
//        configKey = "accounting",
//        configName = "核算",
//        gmtModified = "2020-11-21 08:29:10",
//        modifiedBy = "04b7e539c77d4bdbb4fe4e87eaaf41e4",
//        type = "app",
//        code = "0dc8ac22c72a4155a5c4d8c7b6dfdb0d",
//        deleted = 0,
//        createdBy = "ca796ec21a7a443994ad81977fb79e1e",
//        configValue = "1",
//        gmtCreated = "2020-11-20 19:29:16",
//    },
//        {
//        id = "4393",
//        roleCode = "0e02dfb8b9fe447785985ba87d8c16d2",
//        configDesc = "待开票：0-否，1-是",
//        configKey = "apply_for_money",
//        configName = "货主打款",
//        gmtModified = "2020-11-21 08:29:10",
//        modifiedBy = "04b7e539c77d4bdbb4fe4e87eaaf41e4",
//        type = "app",
//        code = "e7b1c6b8aa794187b1e7a3854e24753e",
//        deleted = 0,
//        createdBy = "ca796ec21a7a443994ad81977fb79e1e",
//        configValue = "0",
//        gmtCreated = "2020-11-20 19:29:16",
//    },
//        {
//        id = "4394",
//        roleCode = "0e02dfb8b9fe447785985ba87d8c16d2",
//        configDesc = "待开票：0-否，1-是",
//        configKey = "withdrawal_application",
//        configName = "提现申请",
//        gmtModified = "2020-11-21 08:29:10",
//        modifiedBy = "04b7e539c77d4bdbb4fe4e87eaaf41e4",
//        type = "app",
//        code = "0b06fca6fe274be788ed5e3da63dd190",
//        deleted = 0,
//        createdBy = "ca796ec21a7a443994ad81977fb79e1e",
//        configValue = "0",
//        gmtCreated = "2020-11-20 19:29:16",
//    },
//),

// 0 不展示  其他情况展示

/// 获取 appRole配置列表
+ (NSArray *)getAppRoleConfig{
    
    NSDictionary *dic = [CJControl getPartyUserCenter];
    
    if (dic == nil || IsNilOrNull(dic) ) {
        return nil;
    }else {
     
        NSArray *list = dic[@"appRoleConfig"];
        
        if (IsNilOrNull(list) || list.count == 0) {
            return nil;
        }else{
            return list;
        }
    }

    return nil;
}

+ (BOOL)getAppRoleConfigValuelist:(NSArray *)list by:(NSString *)key{
    
    __block NSString *strCode = @"";
    [list enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        
        NSDictionary *dic = list[idx];
        NSString *configKey = [CJControl getThreeUnaryValueStr:dic[@"configKey"]];
        
        if ([configKey isEqualToString:key]) {
            strCode = [CJControl getThreeUnaryValueStr:dic[@"configValue"]];
        }
        
    }];
    
    if ([strCode isEqualToString:@"0"]) {
        return YES;
    }else{
        return NO;
    }
    
}

/// （企业）员工是否隐藏核算按钮  只有  configValue == 0  返回YES隐藏其他均展示
+ (BOOL)getIsHideAcccountPrice{
    
    NSArray *list = [CJControl getAppRoleConfig];
    
    if (IsNilOrNull(list)) {
        return NO;
    }else{
        return [CJControl getAppRoleConfigValuelist:list by:@"accounting"];
    }
    
    return NO;
}

/// （企业）员工是否货主打款核算按钮  只有  configValue == 0  返回YES隐藏其他均展示
+ (BOOL)getIsHideApplyRemit{
    
    NSArray *list = [CJControl getAppRoleConfig];
    
    if (IsNilOrNull(list)) {
        return NO;
    }else{
        return [CJControl getAppRoleConfigValuelist:list by:@"apply_for_money"];
    }
    
    return NO;
}

#pragma mark ----- 个人中心 余额支付免验状态

// 免验授权，userCenter接口有 merchSign：授权状态，0待授权（默认），1授权中，2已授权，3授权失败  merchSignType  0未进行过授权1线上授权 2线下授权    merchSign=0 &(merchSignType=0||merchSignType=1) 点击按钮访问接口  签约授权接口

+ (NSString *)getAccountBalanceVisafreeAuthStatus{
    
//    merchSign：授权状态，0待授权（默认），1授权中，2已授权，3授权失败
    NSDictionary *dic = [CJControl getPartyUserCenter];
    NSString *strCode = [CJControl getThreeUnaryValueStr:dic[@"merchSign"]];
    
    switch ([strCode intValue]) {
        case 0:
            return @"待授权";
            break;
        case 1:
            return @"授权中";
            break;
        case 2:
            return @"已授权";
            break;
        case 3:
            return @"授权失败";
            break;
        default:
            return @"待授权";
            break;
    }
    
}

/// 是否调用授权接口
+ (BOOL)getWhetherCallVisaFreeApi{
    
//    merchSign=0 &(merchSignType=0||merchSignType=1)调用
    NSDictionary *dic = [CJControl getPartyUserCenter];
    NSString *strMerchSign = [CJControl getThreeUnaryValueStr:dic[@"merchSign"]];
    NSString *strMerchSignType = [CJControl getThreeUnaryValueStr:dic[@"merchSignType"]];
    
    if ([strMerchSign intValue] == 0 && ([strMerchSignType intValue] == 0 || [strMerchSignType intValue] == 1)) {
        return YES;
    }else{
        return NO;
    }
}
//展示 免验授权
+ (BOOL)getShowAccountBalanceVisafree{
//    staffType   0 或者 1 显示
//    NSDictionary *dic = [CJControl getPartyUserCenter];
//    NSString *strMerchSign = [CJControl getThreeUnaryValueStr:dic[@"staffType"]];
//
//    if (([strMerchSign intValue] == 0 || [strMerchSign intValue] == 1) && [CJControl getShowMyBank]) {
//        return YES;
//    }else{
        return NO;
//    }
}


+ (BOOL)getBoolByKeyString:(NSString *)strKey{
    
    NSDictionary *dic = [CJControl getPartyUserCenter];

    if (dic == nil || IsNilOrNull(dic) ) {
        return NO;
    }else {
        NSString *strCode = CJStringWithFormat(@"%@",dic[strKey]);
        if ([strCode isEqualToString:@"1"]) {
            return YES;
        }else{
            return NO;
        }
    }
}




+ (NSString *)getDeviceUUID{
    NSString *appName=[[[NSBundle mainBundle] infoDictionary] objectForKey:(NSString*)kCFBundleNameKey];
    NSString *strApplicationUUID =  [SAMKeychain passwordForService:appName account:@"Shipper"];
    
    if (strApplicationUUID == nil){
        strApplicationUUID  = [[[UIDevice currentDevice] identifierForVendor] UUIDString];
        NSError *error = nil;
        SAMKeychainQuery *query = [[SAMKeychainQuery alloc] init];
        query.service = appName;
        query.account = @"Shipper";
        query.password = strApplicationUUID;
        query.synchronizationMode = SAMKeychainQuerySynchronizationModeNo;
        [query save:&error];
 
    }
    return strApplicationUUID;
}


#pragma mark - base64加密
+ (NSString *) base64:(NSString *) input{
    NSData * data = [input dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
    data = [GTMBase64 encodeData:data];
    NSString * output = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
    return output;
}
#pragma mark - md5加密
+ (NSString *) md5:(NSString *) input {
    const char *cStr = [input UTF8String];
    unsigned char digest[CC_MD5_DIGEST_LENGTH];
    CC_MD5( cStr, strlen(cStr), digest ); // This is the md5 call
    
    NSMutableString *output = [NSMutableString stringWithCapacity:CC_MD5_DIGEST_LENGTH * 2];
    
    for(int i = 0; i < CC_MD5_DIGEST_LENGTH; i++)
        [output appendFormat:@"%02x", digest[i]];
    return  output;
}

/**
 十进制转换十六进制
  
 @param decimal 十进制数
 @return 十六进制数
 */
 + (NSString *)getHexByDecimal:(NSInteger)decimal {
    
    NSString *hex =@"";
    NSString *letter;
    NSInteger number;
    for (int i = 0; i<9; i++) {
        
        number = decimal % 16;
        decimal = decimal / 16;
        switch (number) {
                
            case 10:
                letter =@"a"; break;
            case 11:
                letter =@"b"; break;
            case 12:
                letter =@"c"; break;
            case 13:
                letter =@"d"; break;
            case 14:
                letter =@"e"; break;
            case 15:
                letter =@"f"; break;
            default:
                letter = [NSString stringWithFormat:@"%ld", number];
        }
        hex = [letter stringByAppendingString:hex];
        if (decimal == 0) {
            
            break;
        }
    }
    return hex;
}




+(NSString *)convertToJsonData:(NSArray *)dict{
    NSError *error;
    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dict options:NSJSONWritingPrettyPrinted error:&error];
    NSString *jsonString;
    
    if (!jsonData) {
        DLog(@"%@",error);
    }else{
        jsonString = [[NSString alloc]initWithData:jsonData encoding:NSUTF8StringEncoding];
    }
    NSMutableString *mutStr = [NSMutableString stringWithString:jsonString];
    NSRange range = {0,jsonString.length};
    //去掉字符串中的空格
    //     [mutStr replaceOccurrencesOfString:@" " withString:@"" options:NSLiteralSearch range:range];
    //     NSRange range2 = {0,mutStr.length};
    
    //去掉字符串中的换行符
    [mutStr replaceOccurrencesOfString:@"\n" withString:@"" options:NSLiteralSearch range:range];
    
    return mutStr;
    
}


#pragma mark ----------huoqu tuopian ju-----------

+ (NSString *)getImgFilePath:(UIImage *)img{
    
   
    NSString *fileName = [CJControl saveImage:[CJControl scaleImage:img newSize:CGSizeMake(100, 100)] WithName:[NSString stringWithFormat:@"%@%@",[CJControl generateUuidString],@".jpg"]];
    return fileName;
}

/**
 * 修改图片大小
 */
+ (UIImage *) scaleImage:(UIImage*)image newSize:(CGSize) newSize{
    //    newSize.height=image.size.height*(newSize.width/image.size.width);
    UIGraphicsBeginImageContext(newSize);
    [image drawInRect:CGRectMake(0, 0, newSize.width, newSize.height)];
    UIImage *newImage=UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return  newImage;
}


/**
 * 保存图片
 */
+ (NSString *)saveImage:(UIImage *)tempImage WithName:(NSString *)imageName{
    NSData* imageData;
    
    //判断图片是不是png格式的文件
    if (UIImagePNGRepresentation(tempImage)) {
        //返回为png图像。
        imageData = UIImagePNGRepresentation(tempImage);
    }else {
        //返回为JPEG图像。
        imageData = UIImageJPEGRepresentation(tempImage, 1.0);
    }
    
    NSArray* paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask,YES);
    DLog(@"%@",paths[0]);
    NSString* documentsDirectory = [paths objectAtIndex:0];
    
    NSString* fullPathToFile = [documentsDirectory stringByAppendingPathComponent:imageName];
    
    NSArray *nameAry=[fullPathToFile componentsSeparatedByString:@"/"];
    DLog(@"===fullPathToFile===%@",fullPathToFile);
    DLog(@"===FileName===%@",[nameAry objectAtIndex:[nameAry count]-1]);
    
    [imageData writeToFile:fullPathToFile atomically:NO];
    return fullPathToFile;
}

/**
 * 生成GUID
 */
+ (NSString *)generateUuidString{
    // create a new UUID which you own
    CFUUIDRef uuid = CFUUIDCreate(kCFAllocatorDefault);
    
    // create a new CFStringRef (toll-free bridged to NSString)
    // that you own
    NSString *uuidString = (NSString *)CFBridgingRelease(CFUUIDCreateString(kCFAllocatorDefault, uuid));
    
    // transfer ownership of the string
    // to the autorelease pool
    //[uuidString autorelease];
    
    // release the UUID
    CFRelease(uuid);
    
    return uuidString;
}


+(NSString*)getCurrentTimes{
    
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    
    // ----------设置你想要的格式,hh与HH的区别:分别表示12小时制,24小时制
    
    [formatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
    
    //现在时间,你可以输出来看下是什么格式
    
    NSDate *datenow = [NSDate date];
    
    //----------将nsdate按formatter格式转成nsstring
    
    NSString *currentTimeString = [formatter stringFromDate:datenow];
    
    NSLog(@"currentTimeString =  %@",currentTimeString);
    
    return currentTimeString;
    
}



+(NSString *)convertToJsonDataFromDic:(NSDictionary *)dict{
    
    NSError *error;
    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dict options:NSJSONWritingPrettyPrinted error:&error];
    
    NSString *jsonString;
    
    if (!jsonData) {
        
        DLog(@"%@",error);
        
    }else{
        
        jsonString = [[NSString alloc]initWithData:jsonData encoding:NSUTF8StringEncoding];
        
    }
    
    NSMutableString *mutStr = [NSMutableString stringWithString:jsonString];
    
//    NSRange range = {0,jsonString.length};
    
    
    //去掉字符串中的空格
    
//    [mutStr replaceOccurrencesOfString:@" " withString:@"" options:NSLiteralSearch range:range];
    
//         NSRange range2 = {0,mutStr.length};
    
    //去掉字符串中的换行符
    NSRange range1 = {0,mutStr.length};

    [mutStr replaceOccurrencesOfString:@"\n" withString:@"" options:NSLiteralSearch range:range1];
    
    return mutStr;
    
}
+(NSString *)convertToJsonDataFromArray:(NSArray *)dict
{
    NSError *error;
    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dict options:NSJSONWritingPrettyPrinted error:&error];
    NSString *jsonString;
    
    if (!jsonData) {
        DLog(@"%@",error);
    }else{
        jsonString = [[NSString alloc]initWithData:jsonData encoding:NSUTF8StringEncoding];
    }
    NSMutableString *mutStr = [NSMutableString stringWithString:jsonString];
    NSRange range = {0,jsonString.length};
    //去掉字符串中的空格
    //     [mutStr replaceOccurrencesOfString:@" " withString:@"" options:NSLiteralSearch range:range];
    //     NSRange range2 = {0,mutStr.length};
    
    //去掉字符串中的换行符
    [mutStr replaceOccurrencesOfString:@"\n" withString:@"" options:NSLiteralSearch range:range];
    
    return mutStr;
    
}
+ (void)clickPhoneWithPhoneNum:(NSString *)phone{
    [[UIApplication sharedApplication]openURL:[NSURL URLWithString:CJStringWithFormat(@"tel:%@",phone)]];
}

+ (NSString *)getThreeUnaryValueStr:(id)idx{
    
     NSString *str = CJStringWithFormat(@"%@",idx);
     if ([CJRegular getIsStrEmpty:str] || IsNilOrNull(idx) ||[str isEqualToString:@"null"] ||[str isEqualToString:@"(null)"] ||[str isEqualToString:@"NULL"] ||[str isEqualToString:@"(NULL)"] ||[str isEqualToString:@"nil"] ||[str isEqualToString:@"(nil)"] ||[str isEqualToString:@"NIL"] ||[str isEqualToString:@"(NIL)"]) {
         return @"";
     }else{
         return str;
     }
}


+ (BOOL)getIsEmpty:(id)idx{
    
     NSString *str = CJStringWithFormat(@"%@",idx);
     if ([CJRegular getIsStrEmpty:str] || IsNilOrNull(idx) ||[str isEqualToString:@"null"] ||[str isEqualToString:@"(null)"] ||[str isEqualToString:@"NULL"] ||[str isEqualToString:@"(NULL)"] ||[str isEqualToString:@"nil"] ||[str isEqualToString:@"(nil)"] ||[str isEqualToString:@"NIL"] ||[str isEqualToString:@"(NIL)"]) {
         return YES;
     }else{
         return NO;
     }
}

+ (NSArray *)componentsSeparatedByString:(NSString *)str withSign:(NSString *)sign{
    return [str componentsSeparatedByString:sign];
}

+ (NSString *)stringByReplacingOccurrencesOfString:(NSString *)str{
    
    return [str stringByReplacingOccurrencesOfString:@"," withString:@""];
}


/**
 *  通过 CAShapeLayer 方式绘制虚线
 *
 *  param lineView:       需要绘制成虚线的view
 *  param lineLength:     虚线的宽度
 *  param lineSpacing:    虚线的间距
 *  param lineColor:      虚线的颜色
 *  param lineDirection   虚线的方向  YES 为水平方向， NO 为垂直方向
 **/
+ (void)drawLineOfDashByCAShapeLayer:(UIView *)lineView lineLength:(int)lineLength lineSpacing:(int)lineSpacing lineColor:(UIColor *)lineColor lineDirection:(BOOL)isHorizonal {

    CAShapeLayer *shapeLayer = [CAShapeLayer layer];

    [shapeLayer setBounds:lineView.bounds];

    if (isHorizonal) {

        [shapeLayer setPosition:CGPointMake(CGRectGetWidth(lineView.frame) / 2, CGRectGetHeight(lineView.frame))];

    } else{
        [shapeLayer setPosition:CGPointMake(CGRectGetWidth(lineView.frame) / 2, CGRectGetHeight(lineView.frame)/2)];
    }

    [shapeLayer setFillColor:[UIColor clearColor].CGColor];
    //  设置虚线颜色为blackColor
    [shapeLayer setStrokeColor:lineColor.CGColor];
    //  设置虚线宽度
    if (isHorizonal) {
        [shapeLayer setLineWidth:CGRectGetHeight(lineView.frame)];
    } else {

        [shapeLayer setLineWidth:CGRectGetWidth(lineView.frame)];
    }
    [shapeLayer setLineJoin:kCALineJoinRound];
    //  设置线宽，线间距
    [shapeLayer setLineDashPattern:[NSArray arrayWithObjects:[NSNumber numberWithInt:lineLength], [NSNumber numberWithInt:lineSpacing], nil]];
    //  设置路径
    CGMutablePathRef path = CGPathCreateMutable();
    CGPathMoveToPoint(path, NULL, 0, 0);

    if (isHorizonal) {
        CGPathAddLineToPoint(path, NULL,CGRectGetWidth(lineView.frame), 0);
    } else {
        CGPathAddLineToPoint(path, NULL, 0, CGRectGetHeight(lineView.frame));
    }

    [shapeLayer setPath:path];
    CGPathRelease(path);
    //  把绘制好的虚线添加上来
    [lineView.layer addSublayer:shapeLayer];
}


//+ (UIImage *)addWatermarkToPicture:(UIImage *)image withLoaction:(NSString *)locationString {
//    
////    CGSize imageSize = CGSizeMake(image.size.width, image.size.height);
////    UIGraphicsBeginImageContextWithOptions(imageSize, NO, 0);
////    [image drawAtPoint:CGPointZero];
////    NSString *date = [CJControl getCurrentTimes];
////    NSString *location = locationString;
////    [date drawAtPoint:CGPointMake(imageSize.width - 300, imageSize.height - 100) withAttributes:@{NSFontAttributeName:[UIFont systemFontOfSize:20], NSForegroundColorAttributeName:[UIColor cjMainColor]}];
////    [location drawAtPoint:CGPointMake(imageSize.width - 500, imageSize.height - 50) withAttributes:@{NSFontAttributeName:[UIFont systemFontOfSize:20], NSForegroundColorAttributeName:[UIColor cjMainColor]}];
////    image = UIGraphicsGetImageFromCurrentImageContext();
////    UIGraphicsEndImageContext();
////
////    return image;
//    
//    
//     int w = image.size.width;
//     int h = image.size.height;
//    CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
//    //create a graphic context with CGBitmapContextCreate
//    CGContextRef context = CGBitmapContextCreate(NULL, w, h, 8, 4 * w, colorSpace, kCGImageAlphaPremultipliedFirst);
//    CGContextDrawImage(context, CGRectMake(0, 0, w, h), image.CGImage);
//    CGContextSetRGBFillColor(context, 0.0, 1.0, 1.0, 1);
//    char* text = (char *)[locationString cStringUsingEncoding:NSASCIIStringEncoding];
//    CGContextSelectFont(context, "Georgia", 30, kCGEncodingMacRoman);
//    CGContextSetTextDrawingMode(context, kCGTextFill);
//    CGContextSetRGBFillColor(context, 255, 0, 0, 1);
//    CGContextShowTextAtPoint(context, w/2-strlen(text)*5, h/2, text, strlen(text));
//    //Create image ref from the context
//    CGImageRef imageMasked = CGBitmapContextCreateImage(context);
//    CGContextRelease(context);
//    CGColorSpaceRelease(colorSpace);
//    return [UIImage imageWithCGImage:imageMasked];
//    
//}


/**
 添加字符串水印到图片,水印大小根据图片大小等比设置

 @param originalImage 需要添加水印的图片
 @param text 水印字符串
 @param scale 水印的大小比例,默认1
 @return 添加了水印的图片
 */
+ (UIImage *)watermardImageWithImage:(UIImage *)originalImage text:(NSString *)text watermardScale:(CGFloat)scale{
    
//        CGSize imageSize = CGSizeMake(originalImage.size.width, originalImage.size.height);
//        UIGraphicsBeginImageContextWithOptions(imageSize, NO, 0);
//        [originalImage drawAtPoint:CGPointZero];
//        NSString *date = [CJControl getCurrentTimes];
//        NSString *location = text;
//        [date drawAtPoint:CGPointMake(imageSize.width - 300, imageSize.height - 100) withAttributes:@{NSFontAttributeName:[UIFont systemFontOfSize:20], NSForegroundColorAttributeName:[UIColor cjMainColor]}];
//        [location drawAtPoint:CGPointMake(imageSize.width - 500, imageSize.height - 50) withAttributes:@{NSFontAttributeName:[UIFont systemFontOfSize:20], NSForegroundColorAttributeName:[UIColor cjMainColor]}];
//        originalImage = UIGraphicsGetImageFromCurrentImageContext();
//        UIGraphicsEndImageContext();
//
//        return originalImage;
        
    
    text = CJStringWithFormat(@"%@ \n%@   ",[CJControl getCurrentTimes] ,text);
    CGFloat viewWidth = originalImage.size.width;
      CGFloat viewHeight = originalImage.size.height;
      CGFloat min = MIN(viewWidth, viewHeight);
      CGFloat inScale = min / 1242 * scale;

      CGFloat horizzontalSpace = 200.0 * inScale;
      CGFloat verticalSpace = 150.0 * inScale;
//      CGFloat angle = (M_PI_2/ -2);

      CGFloat fontSize = MAX(10, (70 * inScale));
    fontSize = fontSize * 0.5;
      NSShadow *shadow = [[NSShadow alloc] init];
      [shadow setShadowOffset:CGSizeMake(5 * inScale, 8 * inScale)];
      shadow.shadowColor = [UIColor colorWithRed:0 green:0 blue:0 alpha:0.6];

      //文字的属性
      NSDictionary *attr = @{
                             // 设置字体大小
                             NSFontAttributeName : [UIFont systemFontOfSize:fontSize],
                             // 设置文字颜色
                             NSForegroundColorAttributeName : [UIColor cjMainColor],
                             // 设置阴影
//                             NSShadowAttributeName : shadow
                             };
      NSMutableAttributedString *attrStr = [[NSMutableAttributedString alloc] initWithString:text attributes:attr];
      UIImage *image = [CJControl watermardImageWithImage:originalImage watermark:attrStr horizontalSpace:horizzontalSpace verticalSpace:verticalSpace];
      return image;
}

// 基础方法
+ (UIImage *)watermardImageWithImage:(UIImage *)originalImage watermark:(NSAttributedString *)title horizontalSpace:(CGFloat)horizontalSpace verticalSpace:(CGFloat)verticalSpace {
    if (!originalImage) {
        return originalImage;
    }
    
    if (!title || title.length == 0) {
        return originalImage;
    }
    
    //原始image的宽高
    CGFloat viewWidth = originalImage.size.width;
    CGFloat viewHeight = originalImage.size.height;
    
    //为了防止图片失真，绘制区域宽高和原始图片宽高一样
    UIGraphicsBeginImageContext(CGSizeMake(viewWidth, viewHeight));
    //先将原始image绘制上
    [originalImage drawInRect:CGRectMake(0, 0, viewWidth, viewHeight)];
    //sqrtLength：原始image的对角线length。在水印旋转矩阵中只要矩阵的宽高是原始image的对角线长度，无论旋转多少度都不会有空白。
    CGFloat sqrtLength = sqrt(viewWidth*viewWidth + viewHeight*viewHeight);
    //绘制文字的宽高
    CGFloat strWidth = title.size.width;
    CGFloat strHeight = title.size.height;
    
    //开始旋转上下文矩阵，绘制水印文字
    CGContextRef context = UIGraphicsGetCurrentContext();
    
    //将绘制原点（0，0）调整到源image的中心
    CGContextConcatCTM(context, CGAffineTransformMakeTranslation(viewWidth/2, viewHeight-40));
//    //以绘制原点为中心旋转
//    CGContextConcatCTM(context, CGAffineTransformMakeRotation(angle));
//    //将绘制原点恢复初始值，保证当前context中心和源image的中心处在一个点(当前context已经旋转，所以绘制出的任何layer都是倾斜的)
//    CGContextConcatCTM(context, CGAffineTransformMakeTranslation(-viewWidth/2, -viewHeight/2));
    
//    //计算需要绘制的列数和行数
//    int horCount = sqrtLength / (strWidth + horizontalSpace) + 1;
//    int verCount = sqrtLength / (strHeight + verticalSpace) + 1;
    
    //此处计算出需要绘制水印文字的起始点，由于水印区域要大于图片区域所以起点在原有基础上移
    CGFloat orignX = -(sqrtLength-viewWidth)/2 + 30;
    CGFloat orignY = -(sqrtLength-viewHeight)/2;
    
//    //在每列绘制时X坐标叠加
    CGFloat tempOrignX = orignX;
    //在每行绘制时Y坐标叠加
    CGFloat tempOrignY = orignY;
//    for (int i = 0; i < horCount * verCount; i++) {
//        [title drawInRect:CGRectMake(tempOrignX, tempOrignY, strWidth, strHeight)];
//        if (i % horCount == 0 && i != 0) {
//            tempOrignX = orignX;
//            tempOrignY += (strHeight + verticalSpace);
//        }else{
//            tempOrignX += (strWidth + horizontalSpace);
//        }
//    }
    
    [title drawInRect:CGRectMake(tempOrignX, tempOrignY, strWidth, strHeight)];

    //根据上下文制作成图片
    UIImage *finalImg = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    CGContextRestoreGState(context);
    return finalImg;
}

+ (UIViewController *)getCurrentViewController{

    UIViewController* currentViewController = [CJControl getRootViewController];
    BOOL runLoopFind = YES;
    while (runLoopFind) {
        if (currentViewController.presentedViewController) {

            currentViewController = currentViewController.presentedViewController;
        } else if ([currentViewController isKindOfClass:[UINavigationController class]]) {

          UINavigationController* navigationController = (UINavigationController* )currentViewController;
            currentViewController = [navigationController.childViewControllers lastObject];

        } else if ([currentViewController isKindOfClass:[UITabBarController class]]) {

          UITabBarController* tabBarController = (UITabBarController* )currentViewController;
            currentViewController = tabBarController.selectedViewController;
        } else {

            NSUInteger childViewControllerCount = currentViewController.childViewControllers.count;
            if (childViewControllerCount > 0) {

                currentViewController = currentViewController.childViewControllers.lastObject;

                return currentViewController;
            } else {

                return currentViewController;
            }
        }

    }
    return currentViewController;
}

+ (UIViewController *)getRootViewController{

    UIWindow* window = [[[UIApplication sharedApplication] delegate] window];
    NSAssert(window, @"The window is empty");
    return window.rootViewController;
}

+(NSString *)replaceStringWithAsterisk:(NSString *)originalStr startLocation:(NSInteger)startLocation lenght:(NSInteger)lenght{

    NSString *newStr = originalStr;

//    for (int i = 0; i < lenght; i++) {
//
//        NSRange range = NSMakeRange(startLocation, 1);
//
//        newStr = [newStr stringByReplacingCharactersInRange:range withString:@"*"];
//
//        startLocation ++;
//
//    }

    return newStr;

}


@end
